#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Joycon 故障排除工具
提供完整的诊断和解决步骤

Author: Assistant
Date: 2024-12-19
"""

import subprocess
import time
import sys
import os

def run_command(cmd, timeout=10):
    """运行命令并返回结果"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        return result.returncode == 0, result.stdout, result.stderr
    except subprocess.TimeoutExpired:
        return False, "", "命令超时"
    except Exception as e:
        return False, "", str(e)

def check_bluetooth_service():
    """检查蓝牙服务状态"""
    print("🔍 检查蓝牙服务状态...")
    
    success, stdout, stderr = run_command("systemctl is-active bluetooth")
    if success and "active" in stdout:
        print("✅ 蓝牙服务正在运行")
        return True
    else:
        print("❌ 蓝牙服务未运行")
        print("   尝试启动蓝牙服务...")
        success, _, _ = run_command("sudo systemctl start bluetooth")
        if success:
            print("✅ 蓝牙服务启动成功")
            return True
        else:
            print("❌ 蓝牙服务启动失败")
            return False

def check_kernel_modules():
    """检查内核模块"""
    print("\n🔧 检查内核模块...")
    
    modules = ['hid-nintendo', 'hid-generic', 'bluetooth']
    all_loaded = True
    
    for module in modules:
        success, stdout, _ = run_command(f"lsmod | grep {module}")
        if success:
            print(f"✅ {module} 模块已加载")
        else:
            print(f"❌ {module} 模块未加载")
            all_loaded = False
            
            if module == 'hid-nintendo':
                print("   尝试加载 hid-nintendo 模块...")
                success, _, _ = run_command("sudo modprobe hid-nintendo")
                if success:
                    print("   ✅ hid-nintendo 模块加载成功")
                    all_loaded = True
                else:
                    print("   ❌ hid-nintendo 模块加载失败")
    
    return all_loaded

def check_bluetooth_devices():
    """检查蓝牙设备"""
    print("\n📱 检查蓝牙设备...")
    
    success, stdout, stderr = run_command("bluetoothctl devices")
    if not success:
        print("❌ 无法获取蓝牙设备列表")
        return False
    
    joycon_found = False
    for line in stdout.split('\n'):
        if 'joy-con' in line.lower() or 'nintendo' in line.lower():
            print(f"✅ 发现 Joycon 设备: {line.strip()}")
            joycon_found = True
    
    if not joycon_found:
        print("❌ 未发现 Joycon 设备")
        return False
    
    return True

def check_input_devices():
    """检查输入设备"""
    print("\n🎮 检查输入设备...")
    
    success, stdout, stderr = run_command("cat /proc/bus/input/devices")
    if not success:
        print("❌ 无法读取输入设备信息")
        return False
    
    joycon_devices = []
    for line in stdout.split('\n'):
        if 'joy' in line.lower() or 'nintendo' in line.lower():
            joycon_devices.append(line.strip())
    
    if joycon_devices:
        print("✅ 发现 Joycon 输入设备:")
        for device in joycon_devices:
            print(f"   {device}")
        return True
    else:
        print("❌ 未发现 Joycon 输入设备")
        return False

def check_pygame_devices():
    """检查 pygame 设备"""
    print("\n🐍 检查 pygame 设备...")
    
    # 创建临时测试脚本
    test_script = """
import pygame
pygame.init()
pygame.joystick.init()
count = pygame.joystick.get_count()
print(f"检测到 {count} 个手柄设备")
for i in range(count):
    joy = pygame.joystick.Joystick(i)
    joy.init()
    print(f"手柄 {i}: {joy.get_name()}")
pygame.quit()
"""
    
    with open("/tmp/pygame_test.py", "w") as f:
        f.write(test_script)
    
    success, stdout, stderr = run_command("python3 /tmp/pygame_test.py")
    os.remove("/tmp/pygame_test.py")
    
    if success:
        print("✅ pygame 设备检查完成:")
        for line in stdout.split('\n'):
            if line.strip():
                print(f"   {line}")
        return "检测到" in stdout and "0 个手柄" not in stdout
    else:
        print("❌ pygame 设备检查失败")
        return False

def provide_solutions():
    """提供解决方案"""
    print("\n" + "="*60)
    print("🔧 解决方案")
    print("="*60)
    
    print("如果 Joycon 无法正常工作，请按以下步骤操作:")
    print()
    print("1. 确保 Joycon 已配对:")
    print("   - 在 Joycon 上按住 SYNC 按钮直到指示灯闪烁")
    print("   - 在系统蓝牙设置中搜索并配对 Joycon")
    print()
    print("2. 加载必要的内核模块:")
    print("   sudo modprobe hid-nintendo")
    print("   sudo modprobe hid-generic")
    print()
    print("3. 重启蓝牙服务:")
    print("   sudo systemctl restart bluetooth")
    print()
    print("4. 重新连接 Joycon:")
    print("   bluetoothctl connect <MAC地址>")
    print()
    print("5. 检查输入设备:")
    print("   cat /proc/bus/input/devices | grep -i joy")
    print()
    print("6. 如果仍然无法工作，尝试:")
    print("   - 重启系统")
    print("   - 检查 Joycon 电池电量")
    print("   - 尝试不同的 Joycon")

def main():
    """主函数"""
    print("Joycon 故障排除工具")
    print("="*60)
    
    # 检查各个组件
    bluetooth_ok = check_bluetooth_service()
    modules_ok = check_kernel_modules()
    devices_ok = check_bluetooth_devices()
    input_ok = check_input_devices()
    pygame_ok = check_pygame_devices()
    
    # 总结
    print("\n" + "="*60)
    print("📊 诊断总结")
    print("="*60)
    
    issues = []
    if not bluetooth_ok:
        issues.append("蓝牙服务问题")
    if not modules_ok:
        issues.append("内核模块问题")
    if not devices_ok:
        issues.append("蓝牙设备问题")
    if not input_ok:
        issues.append("输入设备问题")
    if not pygame_ok:
        issues.append("pygame 设备问题")
    
    if not issues:
        print("✅ 所有检查都通过！Joycon 应该可以正常工作")
        print("如果仍然有问题，请尝试重新配对手柄")
    else:
        print("❌ 发现问题:")
        for issue in issues:
            print(f"   - {issue}")
        
        provide_solutions()

if __name__ == "__main__":
    main() 